module btoolkit.network {
	export class Http {

		/**
		 * 跨域访问：服务器配置：在response里添加
		 * response.setHeader("Access-Control-Allow-Origin", "*"); 
		 */

		public static timeout = 5;

		public static newInstance(): Http {
			var httpManager = new Http();
			return httpManager;
		}

		/**
		 * 仅下载文本文件（任何后缀名），succeedCallback返回参数any，errorCallback返回无参数
		 */
		public loadText(url: string, succeedCallback: Function, errorCallback: Function = null): void {
			var request = new egret.HttpRequest();
			request.once(egret.Event.COMPLETE, (e: egret.Event) => {
				succeedCallback(request.response);
			}, null);
			request.once(egret.IOErrorEvent.IO_ERROR, (e: egret.IOErrorEvent) => {
				console.error("IOError(" + url + "): " + e);
				if (errorCallback != null) {
					errorCallback();
				}
			}, null);
			request.open(url, egret.HttpMethod.GET);
			request.send();
		}

		/**
		* Http的GET方式访问，succeedCallback返回参数any，errorCallback返回无参数
		*/
		public get(url: string, succeedCallback: Function, errorCallback: Function = null): void {
			console.log('--------------get-url:' + url);
			var request = new egret.HttpRequest();
			request.responseType = egret.HttpResponseType.TEXT;
			request.open(url, egret.HttpMethod.GET);
			request.addEventListener(egret.Event.COMPLETE, (e: egret.Event) => {
				console.log('--------------get-res:' + request.response);
				succeedCallback(request.response);
			}, this);
			request.addEventListener(egret.IOErrorEvent.IO_ERROR, (e: egret.IOErrorEvent) => {
				console.error("-------------get IOError(" + url + "): " + e);
				if (errorCallback != null) {
					errorCallback();
				}
			}, this);
			request.send();
		}

		public post(url: string, params: { [key: string]: Object }, succeedCallback: Function, errorCallback: Function = null, requestJson = false) {
			console.log('--------------post-url:' + url);
			var xmlHttp = new XMLHttpRequest();
			xmlHttp.withCredentials = false; //不用认证    
			xmlHttp.onreadystatechange = function () {
				if (xmlHttp.readyState === 4) //4表示准备完成
				{
					if (xmlHttp.status === 200) //200表示回调成功
					{
						console.log('--------------post-res:' + xmlHttp.responseText);
					}
					else {
						console.log("--------------post-error: " + xmlHttp.status);
					}
				}
			};
			xmlHttp.open('POST', url, true);
			if (requestJson) {
				xmlHttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
			} else {
				xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
			}
			if (requestJson) {
				let jsonData = JSON.stringify(params);
				xmlHttp.send(jsonData);
			} else {
				if (params != null) {
					var paramsStr = "";
					for (var key in params) {
						if (paramsStr == '') {
							paramsStr += key + "=" + params[key];
						} else {
							paramsStr += "&" + key + "=" + params[key];
						}
					}
					console.log('--------------post-params:' + paramsStr);
					xmlHttp.send(paramsStr);
				} else {
					xmlHttp.send();
				}
			}
		}

		/**
		* Http的POST方式访问，succeedCallback返回参数any，errorCallback返回错误参数（e:egret.IOErrorEvent）
		*/
		public post2(url: string, params: { [key: string]: Object }, succeedCallback: Function, errorCallback: Function = null, requestJson = false): void {
			console.log('--------------post-url:' + url);
			var request = new egret.HttpRequest();
			request.responseType = egret.HttpResponseType.TEXT;
			request.open(url, egret.HttpMethod.POST);
			if (requestJson) {
				request.setRequestHeader("Content-Type", "application/json");
			} else {
				request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			}
			request.addEventListener(egret.Event.COMPLETE, (e: egret.Event) => {
				console.log('--------------post-res:' + request.response);
				succeedCallback(request.response);
			}, this);
			request.addEventListener(egret.IOErrorEvent.IO_ERROR, (e: egret.IOErrorEvent) => {
				console.error("-------------get IOError(" + url + "): " + e);
				if (errorCallback != null) {
					errorCallback(e);
				}
			}, this);
			if (requestJson) {
				let jsonData = JSON.stringify(params);
				request.send(jsonData);
			} else {
				if (params != null) {
					var paramsStr = "";
					for (var key in params) {
						if (paramsStr == '') {
							paramsStr += key + "=" + params[key];
						} else {
							paramsStr += "&" + key + "=" + params[key];
						}
					}
					console.log('--------------post-params:' + paramsStr);
					request.send(paramsStr);
				} else {
					request.send();
				}
			}
		}

		/**
		 * 从当前URL获取参数
		 */
		public static getParamFromUrl(key: string): string {
			if (window.location) {
				let search = location.search;
				if (search == "") {
					return "";
				}
				search = search.slice(1);
				let searchArr = search.split("&");
				let length = searchArr.length;
				for (let i: number = 0; i < length; i++) {
					let str = searchArr[i];
					let arr = str.split("=");
					if (arr[0] == key) {
						return arr[1];
					}
				}
			}
			return "";
		}

	}
}